import citycode from './citycode.json';

interface NestedItem {
  code: string;
  name: string;
  children: NestedItem[];
}
export const kvCityCode = citycode;

export const plainCityCode = (function plainJson(kv) {
  return Object.keys(kv).map((k) => ({ code: k, name: kvCityCode[k] }));
})(kvCityCode);

export const nestedCityCode: NestedItem[] = (function nestedJson(
  plain: { code: string; name: string }[],
) {
  const json: NestedItem[] = [];
  plain.forEach((val) => val.code.endsWith('0000') && json.push({ ...val, children: [] }));

  // 遍历所有的省 并从数组中取出对应的市
  json.forEach((province) => {
    const provinceCode = province.code.slice(0, 2);

    plain.forEach((val) => {
      if (
        !val.code.endsWith('0000') &&
        val.code.endsWith('00') &&
        val.code.startsWith(provinceCode)
      ) {
        province.children.push({ ...val, children: [] });
      }
    });
  });

  // 遍历所有的市 并从数组中取出对应的区
  json.forEach((province) => {
    if (province.children.length === 0) {
      const cityCode = province.code.slice(0, 2);

      plain.forEach((val) => {
        if (
          !val.code.endsWith('0000') &&
          !val.code.endsWith('00') &&
          !val.code.startsWith('31') &&
          !val.code.startsWith('50') &&
          val.code.startsWith(cityCode)
        ) {
          province.children.push({ ...val, children: [] });
        }
      });
    }

    province.children.forEach((city) => {
      const cityCode = city.code.slice(0, 4);
      plain.forEach((val) => {
        if (
          !val.code.endsWith('0000') &&
          !val.code.endsWith('00') &&
          !val.code.startsWith('11') &&
          !val.code.startsWith('12') &&
          val.code.startsWith(cityCode)
        ) {
          city.children.push({ ...val, children: [] });
        }
      });
    });
  });
  return json;
})(plainCityCode);
